package simi;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SetupModelsServlet extends HttpServlet {

	/**
	 * Need a UID to extend HttpServlet
	 */
	private static final long serialVersionUID = -104043343367177017L;

	public void doPost(HttpServletRequest req, HttpServletResponse res) {

		try {
			HttpSession theSession = req.getSession();

			// Now copy any existing model files to the proper
			// location in the exploded war
			   String homeDirPrefix =
			   SimiPropertyManager.getConfig().getString("files.home");

			// First copy over user-specific models
			String modelsDir = SimiPropertyManager.getConfig().getString(
					"files.models");
			String username = (String) theSession.getAttribute("username");
			theSession.setAttribute("modeldir", homeDirPrefix + username +
				modelsDir); 
			String modelsPath = (String) theSession.getAttribute("modeldir");
			String destPath = getServletConfig().getServletContext()
					.getRealPath("models/" + username);
			// Delete any existing models
			File destDir = new File(destPath);
			ModelFileManager.deleteModelFiles(destDir);
			ModelFileManager.copyUserModelFiles(modelsPath, destPath);

			// Now copy over Global models
			ModelFileManager.copyGlobalModelFiles(modelsDir, destPath);

			// Put Models into session
			List<Model> theModels = ModelFileManager.getModels(destDir);
			theSession.setAttribute(Constants.MODELS, theModels);
			//System.out.println("simi: models have been configured");
			getServletConfig().getServletContext().getRequestDispatcher("/Browser.jsp").forward(req, res);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}